﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace RuoVea.ExFilter;

/// <summary>
/// 对资源型信息进行过滤。常用于防盗链/资源缓存
/// </summary>
public class ResourceFilter : Attribute, IResourceFilter
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void OnResourceExecuted(ResourceExecutedContext context) { }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <exception cref="NotImplementedException"></exception>
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        if (context.IsNonResource()) return;
        #region 防盗链  --特别是一些文件，图片信息时
        string urlReferrer = context.HttpContext.Request.GetRefererUrl(); 
        if (string.IsNullOrWhiteSpace(urlReferrer))//直接访问
            context.Result = new ForbidResult();
        else if (!urlReferrer.Contains("localhost"))//非当前域名
            context.Result = new ForbidResult();
        #endregion
    }
}
